package com.lanting.meetingserver.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lanting.meetingserver.domain.User;

public class CookieHelper {
	
	

	public static boolean isLogin(HttpServletRequest request) {
		
		if(request.getCookies() == null || request.getCookies().length ==0) return false;
	
		for(Cookie ck : request.getCookies())
		{
			if(ck.getName().equalsIgnoreCase("loginId"))
			{
				//return true;
				//DESUtil des = new DESUtil();
				
				//String decodeStr = des.DataDecrypt(ck.getValue());
				String decodeStr = DesUtil.decrypt(ck.getValue());
				if(decodeStr.equalsIgnoreCase(ck.getValue())){
					return false;
				}
				return true;
			}
		}
	
		return false;
	}

	public static Cookie createCookie(User user) {
		String plain =String.format("%d&%s&%s",user.getUserId(),user.getLoginId(),user.getUserEmail());
		//DESUtil des = new DESUtil();
		String cookieStr = DesUtil.encrypt(plain);
		//String cookieStr = des.DataEncrypt(plain);
		
		Cookie ck=new Cookie("loginId",cookieStr);
		ck.setMaxAge(-1);
		ck.setPath("/");
		return ck;
	}
	
	public static void DeleteCookie(HttpServletResponse response){
		Cookie ck = new Cookie("loginId",null);
		ck.setMaxAge(0);
		ck.setPath("/");
		response.addCookie(ck);		
	}
	
	public static int getCurrentId(HttpServletRequest request){
	    for(Cookie ck : request.getCookies()){
			if(ck.getName().equalsIgnoreCase("loginId"))
			{
				//return true;
				//DESUtil des = new DESUtil();
				
				//String decodeStr = des.DataDecrypt(ck.getValue());
				String decodeStr = DesUtil.decrypt(ck.getValue());
				if(decodeStr.equalsIgnoreCase(ck.getValue())){
					return 0;
				}
				String[] ret = decodeStr.split("&");
				return Integer.parseInt(ret[0]);
			}
	    }
	    return 0;
	    
	}

}


